package com.liu.qqRobot.climbingTower.handler;

import cn.hutool.core.codec.Base64;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liu.common.utils.HtmlToImageUtils;
import com.liu.common.utils.QQClientUtils;
import com.liu.mybatisPlus.climbingTower.entity.base.*;
import com.liu.mybatisPlus.climbingTower.service.*;
import com.liu.mybatisPlus.q.service.QGroupUserOperationQuantityService;
import com.liu.qqRobot.event.entity.dto.EventReportingDTO;
import com.liu.qqRobot.q.enums.OperationTypeEnum;
import freemarker.template.TemplateException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Slf4j
@Component
public class ClimbingTowerUseArticleHandler {

    @Resource
    private ClimbingTowerUserArticleService climbingTowerUserArticleService;

    @Resource
    private ClimbingTowerArticleInfoService climbingTowerArticleInfoService;

    @Resource
    private ClimbingTowerArticleAttributesService climbingTowerArticleAttributesService;

    @Resource
    private ClimbingTowerUserInfoService climbingTowerUserInfoService;

    @Resource
    private ClimbingTowerUserEquipService climbingTowerUserEquipService;

    @Resource
    private QGroupUserOperationQuantityService qGroupUserOperationQuantityService;

    /**
     * 处理指令
     * @param data data
     * @param groupId groupId
     * @param userId userId
     * @param isGroup isGroup
     */
    @Transactional
    public void handler(EventReportingDTO.Message.Data data, Long groupId, Long userId, Boolean isGroup) {
        List<String> msgList = new ArrayList<>();
        String articleName = data.getText().replace("爬塔 使用 ", "");
        QueryWrapper<ClimbingTowerArticleInfo> climbingTowerArticleInfoQueryWrapper = new QueryWrapper<>();
        climbingTowerArticleInfoQueryWrapper.eq("name", articleName);
        ClimbingTowerArticleInfo climbingTowerArticleInfo = climbingTowerArticleInfoService.getOne(climbingTowerArticleInfoQueryWrapper);
        if (climbingTowerArticleInfo == null) {
            return;
        }
        QueryWrapper<ClimbingTowerUserArticle> userArticleQueryWrapper = new QueryWrapper<>();
        userArticleQueryWrapper.eq("group_id", groupId);
        userArticleQueryWrapper.eq("user_id", userId);
        userArticleQueryWrapper.eq("article_id", climbingTowerArticleInfo.getId());
        userArticleQueryWrapper.gt("quantity", 0);
        ClimbingTowerUserArticle climbingTowerUserArticle = climbingTowerUserArticleService.getOne(userArticleQueryWrapper);
        if (climbingTowerUserArticle == null) {
            return;
        }
        climbingTowerUserArticle.setQuantity(climbingTowerUserArticle.getQuantity() - 1);
        climbingTowerUserArticleService.updateById(climbingTowerUserArticle);
        QueryWrapper<ClimbingTowerArticleAttributes> climbingTowerArticleAttributesQueryWrapper = new QueryWrapper<>();
        climbingTowerArticleAttributesQueryWrapper.eq("article_id", climbingTowerArticleInfo.getId());
        List<ClimbingTowerArticleAttributes> climbingTowerArticleAttributesList = climbingTowerArticleAttributesService.list(climbingTowerArticleAttributesQueryWrapper);
        QueryWrapper<ClimbingTowerUserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.eq("group_id", groupId);
        userInfoQueryWrapper.eq("user_id", userId);
        ClimbingTowerUserInfo climbingTowerUserInfo = climbingTowerUserInfoService.getOne(userInfoQueryWrapper);
        Integer oldHp = climbingTowerUserInfo.getHp();
        Integer oldAggressivity = climbingTowerUserInfo.getAggressivity();
        QueryWrapper<ClimbingTowerUserEquip> climbingTowerUserEquipQueryWrapper = new QueryWrapper<>();
        climbingTowerUserEquipQueryWrapper.eq("group_id", groupId);
        climbingTowerUserEquipQueryWrapper.eq("user_id", userId);
        ClimbingTowerUserEquip climbingTowerUserEquip = climbingTowerUserEquipService.getOne(climbingTowerUserEquipQueryWrapper);
        switch (climbingTowerArticleInfo.getArticleType()) {
            case "drug" -> {
                msgList.add("使用物品【" + climbingTowerArticleInfo.getName() + "】");
                climbingTowerArticleAttributesList.forEach(climbingTowerArticleAttributes -> {
                    int value = Integer.parseInt(climbingTowerArticleAttributes.getValue());
                    switch (climbingTowerArticleAttributes.getKey()) {
                        case "hp" -> {
                            climbingTowerUserInfo.setHp(climbingTowerUserInfo.getHp() + value);
                        }
                        case "aggressivity" -> {
                            climbingTowerUserInfo.setAggressivity(climbingTowerUserInfo.getAggressivity() + value);
                        }
                        case "agile" -> {
                            climbingTowerUserInfo.setAgile(climbingTowerUserInfo.getAgile() + value);
                        }
                    }
                });
            }
            case "equip" -> {
                switch (climbingTowerArticleInfo.getPosition()) {
                    case "hand" -> {
                        Integer leftHand = climbingTowerUserEquip.getLeftHand();
                        Integer rightHand = climbingTowerUserEquip.getRightHand();
                        if (leftHand == null) {
                            climbingTowerUserEquip.setLeftHand(climbingTowerArticleInfo.getId());
                            msgList.add("装备左手物品【" + climbingTowerArticleInfo.getName() + "】");
                        } else if (rightHand == null) {
                            climbingTowerUserEquip.setRightHand(climbingTowerArticleInfo.getId());
                            msgList.add("装备右手物品【" + climbingTowerArticleInfo.getName() + "】");
                        }
                    }
                    case "head" -> {
                        Integer head = climbingTowerUserEquip.getHead();
                        if (head == null) {
                            climbingTowerUserEquip.setHead(climbingTowerArticleInfo.getId());
                            msgList.add("装备头部物品【" + climbingTowerArticleInfo.getName() + "】");
                        }
                    }
                    case "body" -> {
                        Integer body = climbingTowerUserEquip.getBody();
                        if (body == null) {
                            climbingTowerUserEquip.setBody(climbingTowerArticleInfo.getId());
                            msgList.add("装备身体物品【" + climbingTowerArticleInfo.getName() + "】");
                        }
                    }
                    case "leg" -> {
                        Integer leftLeg = climbingTowerUserEquip.getLeftLeg();
                        Integer rightLeg = climbingTowerUserEquip.getRightLeg();
                        if (leftLeg == null) {
                            climbingTowerUserEquip.setLeftLeg(climbingTowerArticleInfo.getId());
                            msgList.add("装备左腿物品【" + climbingTowerArticleInfo.getName() + "】");
                        } else if (rightLeg == null) {
                            climbingTowerUserEquip.setRightLeg(climbingTowerArticleInfo.getId());
                            msgList.add("装备右腿物品【" + climbingTowerArticleInfo.getName() + "】");
                        }
                    }
                    case "foot" -> {
                        Integer leftFoot = climbingTowerUserEquip.getLeftFoot();
                        Integer rightFoot = climbingTowerUserEquip.getRightFoot();
                        if (leftFoot == null) {
                            climbingTowerUserEquip.setLeftFoot(climbingTowerArticleInfo.getId());
                            msgList.add("装备左脚物品【" + climbingTowerArticleInfo.getName() + "】");
                        } else if (rightFoot == null) {
                            climbingTowerUserEquip.setRightFoot(climbingTowerArticleInfo.getId());
                            msgList.add("装备右脚物品【" + climbingTowerArticleInfo.getName() + "】");
                        }
                    }
                }
            }
        }
        if (!Objects.equals(oldHp, climbingTowerUserInfo.getHp())) {
            msgList.add("血量提升：" + oldHp + "→" + climbingTowerUserInfo.getHp());
        }
        if (!Objects.equals(oldAggressivity, climbingTowerUserInfo.getAggressivity())) {
            msgList.add("攻击力提升：" + oldAggressivity + "→" + climbingTowerUserInfo.getAggressivity());
        }
        climbingTowerUserInfoService.updateById(climbingTowerUserInfo);
        climbingTowerUserEquipService.updateById(climbingTowerUserEquip);
        Map<String, Object> templateParam = new HashMap<>();
        templateParam.put("msgList", msgList);
        try {
            HtmlToImageUtils.htmlToImage("climbingTowerUseArticleTemplate.html", templateParam,
                    "src/main/resources/picture/climbingTowerUseArticle.png", 1500);
            File file = new File("src/main/resources/picture/climbingTowerUseArticle.png");
            String encode = Base64.encode(file);
            String msg = "[CQ:at,qq=" + userId + "]\n[CQ:image,file=base64://" + encode+ ",type=show,subType=0]";
            QQClientUtils.sendMsg(msg, userId, groupId, isGroup);
            qGroupUserOperationQuantityService.statisticsOperationQuantityByType(groupId, userId, OperationTypeEnum.CLIMBING_TOWER_USE_ARTICLE);
        } catch (IOException | ParserConfigurationException | SAXException | TemplateException e) {
            log.error("获取爬塔使用物品展示模板失败:{}", e.getMessage(), e);
        }
    }
}
